﻿/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\MicrosoftAjax.js" />
/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.core.debug.js" />
/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.debug.js" />

/// <reference path="../JQuery/jquery-1.7.2.js" />
/// <reference path="../JQuery/jquery-1.7.2-vsdoc.js" />
/// <reference path="../JQuery/SPServices/jquery.SPServices-0.7.1a.js" />


/**
* Add the reference to SP.js
*/

$(document).ready(function () {
    window.ExecuteOrDelayUntilScriptLoaded(runSPOnLoad, "sp.js");
});

/**
* Code called from ExecuteOrDelayUntilScriptLoaded
* Just tries to get the client context and calls onGetClientContextSucceeded if found
* The function onQuerySuceeded does the logig.
*/
function runSPOnLoad() {
    // ReSharper disable InconsistentNaming
   var clientContext = new window.SP.ClientContext.get_current();
    // ReSharper restore InconsistentNaming
   if (clientContext != undefined && clientContext != null) {
      clientContext.executeQueryAsync(
         Function.createDelegate(this, this.onGetClientContextSucceeded), 
         Function.createDelegate(this, this.onGetClientContextFailed));
   }
}

/**
* If context and sp.js script could be loaded the function onGetClientContextSucceeded looks for a content 
* type called "SPWiki" within the current library, list or whatever. 
* Normaly only a SPWiki document library should contain this content type.
* When found the function replaceDispExClick...() will be called to do some replacements within the HTML using JQuery 
* if content type could be found.
*/
function onGetClientContextSucceeded() {
   $(document).ready(function () {
      if (CheckListForSpWikiContentType() == true) {
         replaceDispExClickInSpWikiLibraries();
      } else {
         replaceDispExClickInListViewWebparts();
      }
   });
   $(".s4-ctx").mouseout(function () { replaceDispExClickAfterContextmenuClick(); });
}

/**
* Function called when no client context could not be foud. Not in use .
*/
function onGetClientContextFailed() { ; }

/**
* Using SPServices to Get the Display Names for a SharePoint List’s Content Types from a current List and checks if SPWiki is used.
* See http://sympmarc.com/2011/02/11/using-spservices-to-get-the-display-names-for-a-sharepoint-lists-content-types/
* See the MSDN SDK at http://msdn.microsoft.com/en-us/library/lists.lists.getlistcontenttypes.aspx for details on this operation
* The SPListNameFromUrl function gets the list name for the current context based on the URL
*/
function CheckListForSpWikiContentType() {
    var contentTypeNamValue = 'SpWiki'; // This vale MUST be the exact name of the SPWiki Content Name.
    var contentTypeNameFound = ""; // Define a variable to hold the name of the Content Type.
    var listNameFromUrl = $().SPServices.SPListNameFromUrl(); // The Guid of the list.

    $().SPServices({
        operation: "GetListContentTypes",
        listName: listNameFromUrl,
        async: false,
        completefunc: function(xData) {
            $(xData.responseXML).find("ContentType").each(function() {
                if ($(this).attr("Name") == contentTypeNamValue) {
                    contentTypeNameFound = $(this).attr("Name");
                    return false;
                }
                return true;
            });
        }
    });

    return (contentTypeNameFound == contentTypeNamValue);
}

/**
* Replace DispEx click in SPWiki library pages.
*
* Replace the genuine SharePoint OnClick event within an SPWiki document library item with a custom on click event.
* It uses the library id and the library item id for opening the file within an other view page.
* Be aware that this funcion only works within libraries.
*/
function replaceDispExClickInSpWikiLibraries() {

   var dispExList = $("a[onclick*='return DispEx'][target!='_blank']a[href*='.SPWiki']");
   if (dispExList.length > 0) {

      var listId = $().SPServices.SPListNameFromUrl();  // The list ID
      var currentSite = $().SPServices.SPGetCurrentSite(); // The current site url
      var viewSpWikiAspx = "/_layouts/SpWiki/Forms/View.aspx"; // The view page
      var querryParamListId = "?SpWikiList=" + listId; // The 1. "?" query part

      dispExList.each(function () {
         var itemId = $(this).parent("div:first").attr('id'); // The item Id
         var querryParamItemId = "&SpWikiID=" + itemId; // The 2. "&" query part
         var url = currentSite + viewSpWikiAspx + querryParamListId + querryParamItemId; // The full url
         $(this).removeAttr("href").removeAttr("onclick").attr("href", url);
      });
   }
}

/**
* List Webpart pages.
*
* Replace the OnClick event of an document library item wirh a custom on click event
* It uses the file name and the list item id for opening the file within an other page
* This funcion only works outside libraries, e.g. on listitem webparts
*/
function replaceDispExClickInListViewWebparts() {

   var dispExList = $("a[onclick*='return DispEx'][target!='_blank']a[href*='.SPWiki']");
   if (dispExList.length > 0) {

      var currentSite = $().SPServices.SPGetCurrentSite(); // The current site url
      var viewSpWikiAspx = "/_layouts/SpWiki/Forms/View.aspx"; // The view page

      dispExList.each(function () {
          var querryParamListId = "?SPWikiLibrayUrl=" + hexEncode(this.href);  // The 1. "?" query part
         var itemId = $(this).parent("div:first").attr('id'); // The item Id
         var querryParamItemId = "&SpWikiID=" + itemId; // The 2. "&" query part
         var url = currentSite + viewSpWikiAspx + querryParamListId + querryParamItemId; // The full url
         $(this).removeAttr("href").removeAttr("onclick").attr("href", url);
      });
   }
}


/**
* When using the library context menu for an exot the link will be reset to default.
*
* Replace the OnClick event of an document library item wirh a custom on click event
* It uses the file name and the list item id for opening the file within an other page
* This funcion only works outsiede libraries, e.g. on listitem webparts
*/
function replaceDispExClickAfterContextmenuClick() {
   var dispExList = $("a[onclick*='return DispEx']a[href*='.SPWiki']");
   if (dispExList.length > 0) {

      var currentSite = $().SPServices.SPGetCurrentSite(); // The current site url
      var viewSpWikiAspx = "/_layouts/SpWiki/Forms/View.aspx"; // The view page

      dispExList.each(function () {
          var querryParamListId = "?SPWikiLibrayUrl=" + hexEncode(this.href);  // The 1. "?" query part
         var itemId = $(this).parent("div:first").attr('id'); // The item Id
         var querryParamItemId = "&SpWikiID=" + itemId; // The 2. "&" query part
         var url = currentSite + viewSpWikiAspx + querryParamListId + querryParamItemId; // The full url
         $(this).removeAttr("href").removeAttr("onclick").attr("href", url);
      });
   }
}

/**
* Encodes data to Hex(base16) format
*/
function hexEncode(data) {
    
    var base16Digits = '0123456789abcdef';
    var base16Map = new Array();
    var i;
    
    for (i = 0; i < 256; i++) { base16Map[i] = base16Digits.charAt(i >> 4) + base16Digits.charAt(i & 15); }
    
    var result = new Array();
    for (i = 0; i < data.length; i++) { result[i] = base16Map[data.charCodeAt(i)]; }
    
    return result.join('');
}


/**
* Decodes Hex(base16) formated data
*/
function hexDecode(data) {
    
    var base16Digits = '0123456789abcdef';
    var base16Map = new Array();
    var i;
    
    for (i = 0; i < 256; i++) {
        base16Map[base16Digits.charAt(i >> 4) + base16Digits.charAt(i & 15)] = String.fromCharCode(i);
    }
    
    if (!data.match( /^[a-f0-9]*$/i )) return false; // return false if input data is not a valid Hex string
    
    if (data.length % 2) data = '0' + data;
    var result = new Array();
    var j = 0;
    for (i = 0; i < data.length; i += 2) { result[j++] = base16Map[data.substr(i, 2)]; }
    
    return result.join('');
}


function NavigateToUrl(url) {
    window.location = url;
}